import User from "../models/user.model.js";
import bcryptjs from "bcryptjs";
import Jwt from "jsonwebtoken";

export const signin = async (req, res, next) => {
  const { email, password } = req.body;
  try {
    let validUser = await User.findOne({ email });
    if (!validUser) return res.json({ message: "User not found!" });
    const validPassword = bcryptjs.compareSync(password, validUser.password);
    if (!validPassword) return next(errorHandler(401, "Wrong credentials!"));
    const token = Jwt.sign({ id: validUser._id }, "ok");
    const { password: pass, ...others } = validUser._doc; // 剔除password
    res.status(200).json({ others, message: "succes", token });
  } catch (error) {
    next(error);
  }
};

export const signup = async (req, res, next) => {
  const { username, email, password } = req.body;
  let validUser = await User.findOne({ email });
  if (validUser) return res.json({ message: "User already exists!" });
  const hashedPassword = bcryptjs.hashSync(password, 10);
  const newUser = new User({ username, email, password: hashedPassword });
  try {
    await newUser.save();
    res.status(201).json("User created successfully!");
  } catch (error) {
    next(error);
  }
};
